package org.example.service;

import com.fasterxml.jackson.databind.node.ArrayNode;
import jakarta.servlet.http.HttpServletRequest;
import org.example.Contant.BusinessException;
import org.example.dto.ResumeAnalysisResponse;
import org.example.service.fileprocessor.FileProcessor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class ResumeAnalysisService {

    private final AIService aiService;
    private final List<FileProcessor> fileProcessors;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    public ResumeAnalysisService(AIService aiService, List<FileProcessor> fileProcessors) {
        this.aiService = aiService;
        this.fileProcessors = fileProcessors;
    }

    public ResumeAnalysisResponse analyzeResumeFile(MultipartFile file, String additionalInfo, int userId) {
        try {
            // 1. 验证文件类型
            String contentType = file.getContentType();
            if (!isSupportedFileType(contentType)) {
                return createErrorResponse("只支持PDF和Word文档格式");
            }

            // 2. 提取文件文本内容
            String resumeText = extractTextFromFile(file, contentType);
            if (resumeText == null || resumeText.trim().length() < 50) {
                return createErrorResponse("提取的简历文本过短或无有效内容");
            }
            // 3. 组合提示词（包含补充信息）
            String fullPrompt = buildFullPrompt(resumeText, additionalInfo);
            // 4. 调用AI分析
            JsonNode aiJson = aiService.analyzeResumeText(fullPrompt,userId);
            // 5. 转换为前端需要的格式
            ObjectNode result = convertToFrontendFormat(aiJson);
            return createSuccessResponse(result);
        } catch (Exception e) {
            return createErrorResponse("简历解析失败: " + e.getMessage());
        }
    }

//    public String analyzeResumeFile(MultipartFile file, String additionalInfo, int userId) {
//        try {
//            // 1. 验证文件类型
//            String contentType = file.getContentType();
//            if (!isSupportedFileType(contentType)) {
//                throw new BusinessException("500","只支持PDF和Word文档格式");
//            }
//
//            // 2. 提取文件文本内容
//            String resumeText = extractTextFromFile(file, contentType);
//            if (resumeText == null || resumeText.trim().length() < 50) {
//                throw new BusinessException("500","提取的简历文本过短或无有效内容");
//            }
//            // 3. 组合提示词（包含补充信息）
//            String fullPrompt = buildFullPrompt(resumeText, additionalInfo);
//            // 4. 调用AI分析
//            String result = aiService.analyzeResumeText(fullPrompt, userId);
//
//            return result;
//        } catch (Exception e) {
//            throw new BusinessException("500",e.getMessage());
//        }
//    }

    private boolean isSupportedFileType(String contentType) {
        return contentType != null &&
                (contentType.equals("application/pdf") ||
                        contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
    }

    private String extractTextFromFile(MultipartFile file, String contentType) throws Exception {
        for (FileProcessor processor : fileProcessors) {
            if (processor.supports(contentType)) {
                return processor.extractText(file.getInputStream());
            }
        }
        throw new UnsupportedOperationException("不支持的文件类型: " + contentType);
    }

    private String buildFullPrompt(String resumeText, String additionalInfo) {
        // 基本提示词
        String prompt = "你是一个专业的简历解析AI。根据以下简历文本分析这个简历，并严格按照指定的JSON格式输出结果，并且给一个关于Java开发岗的适配度。\n\n" +
                "简历文本:\n" + resumeText + "\n\n" +
                "输出要求:\n" +
                "{\n" +
                "  \"姓名\": \"\",\n" +
                "  \"联系方式\": {\n" +
                "    \"电话\": \"\",\n" +
                "    \"邮箱\": \"\"\n" +
                "  },\n" +
                "  \"教育经历\": [\n" +
                "    {\n" +
                "      \"学校\": \"\",\n" +
                "      \"时间\": \"\",\n" +
                "      \"专业\": \"\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"工作经历\": [\n" +
                "    {\n" +
                "      \"项目名称\": \"\",\n" +
                "      \"时间\": \"\",\n" +
                "      \"角色\": \"\",\n" +
                "      \"技术栈\": \"\",\n" +
                "      \"负责功能\": [\"\"]\n" +
                "    }\n" +
                "  ]\n" +
                "}\n\n" +
                "注意:\n" +
                "1. 只返回JSON，不要包含任何额外文本\n" +
                "2. 时间格式保持原文格式\n" +
                "3. 如果信息缺失，对应字段留空\n" +
                "4. 工作经历优先提取项目经历\n" +
                "5. 处理可能的格式问题：表格内容、换行符、特殊字符";
//        String prompt = "你是一个专业的简历解析AI。根据以下简历文本分析这个简历，给一个关于Java开发岗的适配度。\n\n" +
//            "简历文本:\n" + resumeText + "\n\n";

        // 添加补充信息（如果用户提供了）
        if (additionalInfo != null && !additionalInfo.trim().isEmpty()) {
            prompt += "\n\n补充信息:\n" + additionalInfo;
        }

        return prompt;
    }

    private ObjectNode convertToFrontendFormat(JsonNode aiJson) {
        ObjectNode result = objectMapper.createObjectNode();

        // 1. 姓名
        if (aiJson.has("姓名")) {
            result.put("name", aiJson.path("姓名").asText());
        }

        // 2. 联系方式
        ObjectNode contact = objectMapper.createObjectNode();
        if (aiJson.has("联系方式")) {
            JsonNode contactNode = aiJson.path("联系方式");
            if (contactNode.has("电话")) {
                contact.put("phone", contactNode.path("电话").asText());
            }
            if (contactNode.has("邮箱")) {
                contact.put("email", contactNode.path("邮箱").asText());
            }
        }
        result.set("contact", contact);

        // 3. 教育经历
        ArrayNode educationArray = objectMapper.createArrayNode();
        if (aiJson.has("教育经历") && aiJson.path("教育经历").isArray()) {
            for (JsonNode edu : aiJson.path("教育经历")) {
                ObjectNode education = objectMapper.createObjectNode();
                if (edu.has("学校")) education.put("school", edu.path("学校").asText());
                if (edu.has("时间")) education.put("time", edu.path("时间").asText());
                if (edu.has("专业")) education.put("major", edu.path("专业").asText());
                educationArray.add(education);
            }
        }
        result.set("education", educationArray);

        // 4. 工作经历
        ArrayNode workArray = objectMapper.createArrayNode();
        if (aiJson.has("工作经历") && aiJson.path("工作经历").isArray()) {
            for (JsonNode work : aiJson.path("工作经历")) {
                ObjectNode workItem = objectMapper.createObjectNode();
                if (work.has("项目名称")) workItem.put("projectName", work.path("项目名称").asText());
                if (work.has("时间")) workItem.put("time", work.path("时间").asText());
                if (work.has("角色")) workItem.put("role", work.path("角色").asText());
                if (work.has("技术栈")) workItem.put("techStack", work.path("技术栈").asText());

                ArrayNode responsibilities = objectMapper.createArrayNode();
                if (work.has("负责功能") && work.path("负责功能").isArray()) {
                    for (JsonNode func : work.path("负责功能")) {
                        responsibilities.add(func.asText());
                    }
                }
                workItem.set("responsibilities", responsibilities);

                workArray.add(workItem);
            }
        }
        result.set("workExperience", workArray);

        // 5. 技能（从工作经历的技术栈中提取）
        ArrayNode skillsArray = objectMapper.createArrayNode();
        if (aiJson.has("工作经历") && aiJson.path("工作经历").isArray()) {
            for (JsonNode work : aiJson.path("工作经历")) {
                if (work.has("技术栈")) {
                    String techStack = work.path("技术栈").asText();
                    // 简单分割技术栈字符串
                    String[] skills = techStack.split("[,、]");
                    for (String skill : skills) {
                        String trimmed = skill.trim();
                        if (!trimmed.isEmpty()) {
                            skillsArray.add(trimmed);
                        }
                    }
                }
            }
        }
        result.set("skills", skillsArray);

        return result;
    }

    private ResumeAnalysisResponse createSuccessResponse(JsonNode data) {
        return new ResumeAnalysisResponse(true, "简历解析成功", data);
    }

    private ResumeAnalysisResponse createErrorResponse(String message) {
        return new ResumeAnalysisResponse(false, message, null);
    }

    /**
     * 将查询出来的用户简历和用户的提问拼成一个问题
     * @return
     */
    public String createFullQuestion(String question,String info){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("这是用户的简历：");
        stringBuilder.append(info);
        stringBuilder.append("请你根据以下用户的提问，结合用户的简历信息，给予回答：");
        stringBuilder.append(question);
        System.out.println(stringBuilder);
        return stringBuilder.toString();
    }
}
